# coding:utf-8
# @Time    : 2018/9/30 3:49
# @Author  : 0x007er
# @File    : zgrab.py
# @Software: PyCharm
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class zgrabClass():
    '分布式zgrab'
    def __init__(self,Thread,TimeOut,Port,ReqFile,IPFile,ContainList,ExcludeList,TLS):
        '初始化'
        self.Thread = Thread
        self.TimeOut = TimeOut
        self.Port = Port
        self.ReqFile = ReqFile
        self.IPFile = IPFile
        self.ContainList = ContainList
        self.ExcludeList = ExcludeList
        self.ContainList = ContainList
        self.TLS = TLS
    def shell_exec(self,commands):
        try:
            res = os.popen(commands)
            return res.read()
        except Exception as e:
            print(e)
            return False
    def ES(self):
        '返回排除和包含的命令字符串'
        CS = ''
        ES = ''
        for Contain in self.ContainList:
            CS += ' | grep -E "%s"' % Contain

        for Exclude in self.ExcludeList:
            ES += ' | sed -e "/%s/d"' % Exclude
        return CS + ES
    def getTLS(self):
        if self.TLS == '0':
            return ''
        else:
            return ' --tls '
    def start(self):
        commands = 'rm -rf /var/success.txt\n'
        commands += 'rm -rf /var/failure.txt\n'
        commands += 'rm -rf /var/client/request.txt\n'
        commands += 'rm -rf /var/client/zgrabw.txt\n'
        commands += 'ulimit -n 100000\n'
        commands += 'wget '+self.IPFile+' -O /var/client/zgrabw.txt\n'
        commands += 'wget '+self.ReqFile+' -O /var/client/request.txt\n'
        commands += 'cat /var/client/zgrabw.txt | /usr/local/go/bin/src/github.com/zmap/zgrab/zgrab --port '+self.Port+self.getTLS()+' -timeout='+self.TimeOut+' -senders='+self.Thread+' -data="/var/client/request.txt"'+self.ES()+' > /var/www/html/zgrabres.txt\n\n'
        print commands
        f = open('/var/www/html/z.sh','w')
        f.write(commands)
        f.close()
        self.shell_exec('nohup sh /var/www/html/z.sh > /var/www/html/zlog.txt 2>&1 &')
        res = self.shell_exec('ps -ef')
        if res.find('zgrab') > -1:
            return True
        else:
            return False


'''
'''

